package com.jackrain.nea.fc.cp.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.jackrain.nea.common.PostHandleEvent;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.fc.cp.api.ViewHrEmpSaveCmd;
import com.jackrain.nea.fc.cp.mapper.ViewCempMapper;
import com.jackrain.nea.fc.utils.ObjectToUtil;
import com.jackrain.nea.sys.CommandAdapter;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.util.ValueHolder;
import com.jackrain.nea.web.face.User;
import com.jackrain.nea.web.query.DefaultWebEvent;
import com.jackrain.nea.web.query.QuerySessionImpl;
import com.jackrain.nea.web.security.Security4Utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.exceptions.TooManyResultsException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;

/**
 * HR与FC人员接口-02.人员档案
 *
 * @author WSL
 * @create 2017/12/14
 */
@Slf4j
@Component
@Service(protocol = "dubbo", validation = "true", version = "1.0", group = "cp")
public class ViewHrEmpSaveCmdImpl extends CommandAdapter implements ViewHrEmpSaveCmd {


    @Autowired
    PostHandleEvent postHandleEvent;

    @Override
    public ValueHolder execute(HashMap map) throws NDSException {
        ValueHolder vh = new ValueHolder();
        JSONObject param = JSON.parseObject(JSON.toJSONStringWithDateFormat(map.get("param"), "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue), Feature.OrderedField);
        log.info("ViewHrEmpSaveCmdImpl--param-->{}",param);

        if (null == param || param.size() == 0) {
            throw new NDSException("参数格式错误！");
        }

        // Mapper
        ViewCempMapper viewCempMapper;
        try {
            viewCempMapper = ApplicationContextHandle.getBean(ViewCempMapper.class);
        } catch (Exception e) {
            throw new NDSException("服务启动错误！");
        }

        JSONArray paramArray = param.getJSONArray("data");

        // 字段翻译
        JSONArray errorArray = new JSONArray();
        JSONArray successIds = new JSONArray();
        JSONArray handleTime = new JSONArray();
        for (int i = 0; i < paramArray.size(); i++) {
            JSONObject errorJson = new JSONObject();
            JSONObject paramJson = paramArray.getJSONObject(i);
            Long beginTime = System.currentTimeMillis();
            try {
                // 判断所属部门是否为空  若为空则直接插入组织  若不为空则获取所属部门的上级组织
                if (null == paramJson.getString("CP_C_STORE_ID")) {
                    // 所属组织
                    if (paramJson.containsKey("CP_C_HRORG_ID")) {
                        JSONObject getHrorgId = viewCempMapper.selHrorgId(paramJson.getString("CP_C_HRORG_ID"));
                        if (getHrorgId.getInteger("COUNT") > 1) {
                            throw new NDSException("查询所属组织数据重复！");
                        }
                        if (null == getHrorgId.getLong("ID")) {
                            throw new NDSException("该人员档案所属组织在FC中不存在！");
                        }
                        paramJson.put("CP_C_HRORG_ID", getHrorgId.getLong("ID"));
                    }
                } else {
                    JSONObject getHrorgId = viewCempMapper.selOrgIdByDept(paramJson.getString("CP_C_STORE_ID"));
                    if (getHrorgId.getInteger("COUNT") > 1) {
                        throw new NDSException("查询所属组织数据重复！");
                    }
                    if (null == getHrorgId.getLong("ID")) {
                        // 所属店仓
                        JSONObject getStoreId = viewCempMapper.selStoreId(paramJson.getString("CP_C_STORE_ID"));
                        if (getStoreId.getInteger("COUNT") > 1) {
                            throw new NDSException("查询所属部门数据重复！");
                        }
                        if (null == getStoreId.getLong("ID")) {
                            throw new NDSException("该人员档案所属部门在FC中不存在！");
                        }
                        paramJson.put("CP_C_STORE_ID", getStoreId.getLong("ID"));

                        // 根据店仓查询上级组织
                        getHrorgId = viewCempMapper.selOrgIdByStoreId(getStoreId.getLong("ID"));
                        if (getHrorgId.getInteger("COUNT") > 1) {
                            throw new NDSException("查询所属组织数据重复！");
                        }
                        paramJson.put("CP_C_HRORG_ID", getHrorgId.getLong("CP_C_HRORG_ID"));


                    } else {
                        //所属部门为为组织
                        paramJson.remove("CP_C_STORE_ID");
                        paramJson.put("CP_C_HRORG_ID", getHrorgId.getLong("ID"));
                    }

                }

                // 查询FC中表“职务”【CP_C_JOB】中是否存在HR005_ID=PK_JOB的数据
                if (!ObjectToUtil.isNullOREmpty(paramJson.getString("CP_C_JOB_ID"))) {
                    JSONObject jobJson = viewCempMapper.getJobId(paramJson.getString("CP_C_JOB_ID"));
                    if (jobJson.getInteger("COUNT") > 0) {
                        paramJson.put("CP_C_JOB_ID", jobJson.getLong("ID"));
                    } else {
                        throw new NDSException("当前职务在FC中不存在，传输失败");
                    }
                }

                // 查询FC中表“职等”【CP_C_JOBRANK】中是否存在HR006_ID=PK_JOBRANK的数据
                if (!ObjectToUtil.isNullOREmpty(paramJson.getString("CP_C_JOBRANK_ID"))) {
                    JSONObject jobRankJson = viewCempMapper.getJobRankId(paramJson.getString("CP_C_JOBRANK_ID"));
                    if (jobRankJson.getInteger("COUNT") > 0) {
                        paramJson.put("CP_C_JOBRANK_ID", jobRankJson.getLong("ID"));
                    } else {
                        throw new NDSException("当前职等在FC中不存在，传输失败");
                    }
                }

                // 查询FC中表“职级”【CP_C_POSTGRADE】中是否存在HR007_ID=PK_JOBLEVEL的数据
                if (!ObjectToUtil.isNullOREmpty(paramJson.getString("CP_C_POSTGRADE_ID"))) {
                    JSONObject postGradeJson = viewCempMapper.getPostGradeId(paramJson.getString("CP_C_POSTGRADE_ID"));
                    if (postGradeJson.getInteger("COUNT") > 0) {
                        paramJson.put("CP_C_POSTGRADE_ID", postGradeJson.getLong("ID"));
                    } else {
                        throw new NDSException("当前职级在FC中不存在，传输失败");
                    }
                }


                // 判断FC中表【CP_C_EMP】是否存在HR003_ID=Pk_psndoc
                JSONObject checkJson = viewCempMapper.checkEmp(paramJson.getString("HR003_ID"));
                // 头表ID
                Long objid;
                if (checkJson.getInteger("COUNT") > 0) {
                    // 更新
                    objid = checkJson.getLong("ID");

                    Long storeid = checkJson.getLong("CP_C_STORE_ID");
                    if (null != storeid) {
                        String isSto = viewCempMapper.selIsSto(storeid);
                        if (null != isSto && "STO".equals(isSto)) {
                            if (paramJson.containsKey("ISSALER") && ("N".equals(paramJson.getString("ISSALER")))) {
                                paramJson.put("CP_C_STORE_ID", null);
                                paramJson.put("ENUMNO", null);
                            }
                        }
                    }


                } else {
                    // 新增
                    objid = -1L;
//                    paramJson.put("CREATIONDATE", paramJson.get("MODIFIEDDATE"));
                }
                paramJson.remove("MODIFIEDDATE");
                //是否为分拣员
                String ispicker = paramJson.getString("ISPICKER");
                if ("Y".equals(ispicker)) {
                    paramJson.remove("CP_C_STORE_ID");
                    String eshortno = viewCempMapper.selEshortno(paramJson.getString("ECODE"));
                    //查询其分拣员编号是否为空，空则默认为员工编号
                    if (null == eshortno) {
                        paramJson.put("ESHORTNO", paramJson.getString("ECODE"));
                    }
                }
                JSONObject resultJson = new JSONObject();
                resultJson.put("table", "CP_C_EMP");
                resultJson.put("objid", objid);
                // 头表字段
                JSONObject masterJson = new JSONObject();
                masterJson.put("CP_C_EMP", paramJson);
                resultJson.put("fixcolumn", masterJson);

                User user = Security4Utils.getUser("INTER99999");
                QuerySessionImpl querySession = new QuerySessionImpl(user);
                DefaultWebEvent event = new DefaultWebEvent("hrEmpSave", new HashMap(16));
                event.put("param", resultJson);
                querySession.setEvent(event);
                // 调用人员档案标准服务
                log.debug("人员数据:" + resultJson);
                JSONObject retJo = postHandleEvent.executePostHandle(resultJson, querySession, event, "save");
                if (retJo.get("code") != null && (int) retJo.get("code") < 0) {
                    throw new NDSException("" + retJo.get("message") + retJo.get("error"));
                }
                handleTime.add(retJo.get("spendtime"));
                if (retJo.get("code").equals(-1)) {
                    errorJson.put("key", paramJson.getString("HR003_ID"));
                    if (null == retJo.get("message")) {
                        errorJson.put("message", "标准服务调用异常");
                    } else {
                        errorJson.put("message", retJo.get("message"));
                    }
                    errorArray.add(errorJson);
                    continue;
                }
                successIds.add(paramJson.getString("HR003_ID"));
            } catch (Exception e) {
                Long endTime = System.currentTimeMillis();
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
//                e.printStackTrace(pw);
//                log.error(sw.toString());
                if (e instanceof TooManyResultsException) {
                    errorJson.put("key", paramJson.getString("HR003_ID"));
                    errorJson.put("message", "数据查询重复！");
                    errorArray.add(errorJson);
                } else if (e instanceof NDSException) {
                    errorJson.put("key", paramJson.getString("HR003_ID"));
                    errorJson.put("message", e.getMessage() == null ? "标准服务调用异常" : e.getMessage());
                    errorArray.add(errorJson);
                } else {
                    errorJson.put("key", paramJson.getString("HR003_ID"));
                    errorJson.put("message", sw.toString());
                    errorArray.add(errorJson);
                }
                handleTime.add(endTime - beginTime);
            }

        }

        if (errorArray.size() > 0) {
            vh.put("error", errorArray);
            vh.put("code", -1);
        }

        vh.put("spendtime", handleTime);
        vh.put("successIds", successIds);

        return vh;
    }
}
